<?php

class Template {
	
	//模板主题
	protected $theme = 'default';
	
	//模板变量
	protected $_vars = array();
	
	/*
	 * 设置或返回当前主题
	 * access	public
	 * return	string or void
	 */
	public function theme($theme = NULL)
	{
		if ($theme === NULL)
		{
			return $this->theme;
		}
		else
		{
			$this->theme = trim($theme, '/');
		}
	}
	
	/*
	 * 往视图添加数据,如果data是个数组，则是循环添加这个数组
	 * @access	public
	 * @param	$data array|string 变量名
	 * @param	value mixed 变量值
	 */
	public function assign($data, $value = NULL)
	{
		if(is_array($data))
		{
			foreach($data as $k => $v)
			{
				$this->_vars[$k] = $v;
			}
		}
		else
		{
			$this->_vars[$data] = $value;
		}
	}
	
	/*
	 * 获取视图结果
	 * @access	public
	 * @param	$tpl string 模板文件地址，相对于主题目录
	 * @return	string
	 */
	public function fetch($tpl)
	{
		$ci = & get_instance();
		$ci->load->add_view_path(FCPATH.'themes/'.$this->theme);
		$content = $ci->load->view(trim($tpl, '/'), $this->_vars, TRUE);
		$this->replace($content);
		return $content;
	}
	
	/*
	 * 显示视图结果
	 * @access	public
	 * @param	$tpl string 模板文件地址，相对于主题目录
	 * @return	void
	 */
	public function display($tpl)
	{
		$content = $this->fetch($tpl);
		exit($content);
	}
	
	/*
	 * 替换内容
	 * @access	public
	 * @param	$content 原内容
	 * @return	string
	 */
	protected function replace(& $content)
	{
		$ci = & get_instance();
		
		$f = array(
			'__MEMORY__',
			'__TIME__',
			'__SELF__'
		);
		
		$t = array(
			number_format(round(memory_get_usage()/1024/1024, 1), 1, '.', '').'MB',
			$ci->benchmark->elapsed_time('total_execution_time_start', 'total_execution_time_end').'秒',
			current_url()
		);
		
		$content = str_replace($f, $t, $content);
	}
	
}